package com.py.credit.controller;

import com.py.credit.common.XypjConstants;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.DictEntity;
import com.py.credit.service.SysDictService;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典管理Controller
 *
 * @author Leegern
 * @date 2018年4月20日
 */
@RestController
@RequestMapping("/xypjdict")
public class XypjDictController extends SystemController {

    @Autowired
    private SysDictService sysDictService;

    /**
     * 添加字典信息
     *
     * @param
     * @return
     * @author YaoS
     * @date 17:07 18/11/8
     **/
    @RequestMapping(value = "/addDict", method = RequestMethod.POST)
    public RestServiceResult<Object> addDict(@RequestBody DictEntity entity) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        if (null != entity) {
            List<DictEntity> dicList = sysDictService.fineSameDict(entity.getDictKey());
            if (dicList.size() > 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("添加字典信息KEY值重复！");
            } else {
                try {
                    sysDictService.addDict(entity);
                } catch (Exception e) {
                    result.setCode(com.py.credit.common.rest.RestServiceResult.CODE_UNKNOW);
                    result.setMsg("添加字典信息异常！");
                    com.py.credit.common.logs.ExceptionLogger.error("添加字典信息异常！", e.getMessage(), e);
                }
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/queryDictListForPage.json 分页查询字典信息
     * @apiName queryDictListForPage
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {String} dictKey 标识码
     * @apiParam {String} dictName 字典名称
     * @apiParam {int} page 当前页码
     * @apiParam {int} limit 每页条数
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} dictName 字典名称
     * @apiSuccess {String} dictKey 字典KEY值
     * @apiSuccess {String} enabled 是否使用，1否，2是
     * @apiSuccess {String} createTime 创建时间
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":"","count":1,"data":[{"id":1,"createTime":"2018-07-10
     * 11:11:11","delFlag":1,"dictName":"批次反馈类型","dictKey":"PCFK","enabled":2}]}
     */
    @RequestMapping(value = "/queryDictListForPage", method = RequestMethod.POST)
    public RestServiceResult<List<DictEntity>> queryDictListForPage(String dictKey, String dictName, String enabled,
                                                                    String dtlValue, Page page) {
        RestServiceResult<List<DictEntity>> result = new RestServiceResult<>();
        // 分页查询字典信息
        List<DictEntity> datas = sysDictService.queryDictListForPage(dictKey, dictName, enabled, dtlValue, page);
        result.setData(datas);
        result.setCount(page.getTotalCount());
        return result;
    }

    /**
     * @api {post} /sysdict/fineOneDict.json 根据Id查询字典数据
     * @apiName fineOneDict
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {long} id 字典Id
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} dictName 字典名称
     * @apiSuccess {String} dictKey 字典KEY值
     * @apiSuccess {String} enabled 是否使用，1否，2是
     * @apiSuccess {String} createTime 创建时间
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":"","count":1,"data":{"id":1,"createTime":"2018-07-10
     * 11:11:11","delFlag":1,"dictName":"批次反馈类型","dictKey":"PCFK","enabled":2}}
     */
    @RequestMapping(value = "/fineOneDict", method = RequestMethod.POST)
    public RestServiceResult<DictEntity> fineOneDict(long id) {
        DictEntity data = null;
        if (id > XypjConstants.NUMBER_ZERO) {
            // 根据Id查询字典数据
            data = sysDictService.fineOneDict(id);
        }
        return super.getSuccessRestServiceResult(data);
    }

    /**
     * @api {post} /sysdict/updateDict.json 更新字典信息
     * @apiName updateDict
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {DictEntity} entity 字典实体
     * @apiParam {long} id 字典ID
     * @apiParam {String} dictName 字典名称
     * @apiParam {String} dictKey 字典KEY值
     * @apiParam {String} enabled 是否使用，1否，2是
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/updateDict", method = RequestMethod.POST)
    public RestServiceResult<Object> updateDict(@RequestBody DictEntity entity) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();
        if (null != entity) {
            try {
                sysDictService.updateDict(entity);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("更新失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/updateDictStatus.json 批量更新字典数据状态
     * @apiName updateDictStatus
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {long} id 字典Id
     * @apiParam {int} enabled 是否使用，1否，2是
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/updateDictStatus", method = RequestMethod.POST)
    public RestServiceResult<Object> updateDictStatus(long id, int enabled) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        if (id > XypjConstants.NUMBER_ZERO && enabled > XypjConstants.NUMBER_ZERO) {
            try {
                // 批量更新字典数据状态
                sysDictService.batchUpdateDictStatus(Arrays.asList(id), enabled, XypjConstants.NUMBER_ZERO);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("更新失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/batchDelDict.json 批量删除字典数据
     * @apiName batchDelDict
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {String} ids 字典Id集合
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:1 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} result
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/batchDelDict", method = RequestMethod.POST)
    public RestServiceResult<Object> batchDelDict(String ids) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        if (StringUtils.isNotBlank(ids)) {
            try {
                // 批量删除字典数据
                sysDictService.batchUpdateDictStatus(super.convert2Long(ids), XypjConstants.NUMBER_ZERO,
                        XypjConstants.NUMBER_TWO);
            } catch (ServiceException e) {
                result = super.getFailedRestServiceResult(e.getMessage());
                ExceptionLogger.error(e);
            } catch (Exception e) {
                result.setCode(com.py.credit.common.rest.RestServiceResult.CODE_UNKNOW);
                result.setMsg("删除字典数据异常！");
                com.py.credit.common.logs.ExceptionLogger.error("删除字典数据异常！", e.getMessage(), e);

            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/addDictDetail.json 添加字典明细信息
     * @apiName addDictDetail
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {DictDetailEntity} entity 字典明细实体
     * @apiParam {String} dtlKey KEY值
     * @apiParam {String} dtlValue 字典值
     * @apiParam {int} orderBy 排序
     * @apiParam {int} enabled 是否使用，1否，2是
     * @apiParamExample {json} 请求参数示例
     * {"dtlKey":"SEL_KEY","dtlValue":"22","orderBy":1,"enabled":1}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/addDictDetail", method = RequestMethod.POST)
    public RestServiceResult<Object> addDictDetail(@RequestBody DictDetailEntity entity) {
        RestServiceResult<Object> result = new RestServiceResult<>();
        if (null != entity) {
            try {
                sysDictService.addDictDetail(entity);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("添加失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/queryDictDetailListForPage.json 分页查询字典明细信息
     * @apiName queryDictDetailListForPage
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {int} page 当前页码
     * @apiParam {int} limit 每页条数
     * @apiParam {String} dtlKey 字典KEY
     * @apiParam {String} dtlValue 字典值
     * @apiParam {long} dictId 字典Id
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} dtlKey 字典KEY
     * @apiSuccess {String} dtlValue 字典值
     * @apiSuccess {long} dictId 字典Id
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":"","count":1,"data":[{"id":1,"createTime":"2018-07-10
     * 11:11:11","dtlValue":"222","dtlKey":"PCFK","enabled":2}]}
     */
    @RequestMapping(value = "/queryDictDetailListForPage.json", method = RequestMethod.POST)
    public RestServiceResult<List<DictDetailEntity>> queryDictDetailListForPage(
            @RequestParam(value = "dtlKey", required = true, defaultValue = "") String dtlKey,
            @RequestParam(value = "dtlValue", required = true, defaultValue = "") String dtlValue,
            @RequestParam(value = "dictId", required = true, defaultValue = "0") BigInteger dictId, Page page) {
        RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
        // 分页查询字典明细信息
        List<DictDetailEntity> datas = sysDictService.queryDictDetailListForPage(dtlKey, dtlValue, dictId, page);
        result.setData(datas);
        result.setCount(page.getTotalCount());
        return result;
    }

    /**
     * @api {post} /sysdict/fineOneDictDetail.json 根据Id查询字典明细
     * @apiName fineOneDictDetail
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {long} id 字典明细Id
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} dtlKey 字典KEY
     * @apiSuccess {String} dtlValue 字典值
     * @apiSuccess {long} dictId 字典Id
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":"","count":1,"data":{"id":1,"createTime":"2018-07-10
     * 11:11:11","dtlValue":"222","dtlKey":"PCFK","enabled":2}}
     */
    @RequestMapping(value = "/fineOneDictDetail", method = RequestMethod.POST)
    public RestServiceResult<DictDetailEntity> fineOneDictDetail(long id) {
        DictDetailEntity data = null;
        if (id > XypjConstants.NUMBER_ZERO) {
            // 根据Id查询字典明细
            data = sysDictService.fineOneDictDetail(id);
        }
        return super.getSuccessRestServiceResult(data);
    }

    /**
     * @api {post} /sysdict/updateDictDetailStatus.json 批量更新字典明细数据状态
     * @apiName updateDictDetailStatus
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {long} id 字典明细Id
     * @apiParam {int} enabled 是否使用，1否，2是
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/updateDictDetailStatus", method = RequestMethod.POST)
    public RestServiceResult<Object> updateDictDetailStatus(long id, int enabled) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();
        if (id > XypjConstants.NUMBER_ZERO && enabled > XypjConstants.NUMBER_ZERO) {
            try {
                // 批量更新字典明细数据状态
                sysDictService.batchUpdateDictDetailStatus(Arrays.asList(id), enabled, XypjConstants.NUMBER_ZERO);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("更新失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/batchDelDictDetail.json 批量删除字典明细数据
     * @apiName batchDelDictDetail
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {String} ids 字典明细Id集合
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/batchDelDictDetail", method = RequestMethod.POST)
    public RestServiceResult<Object> batchDelDictDetail(String ids) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();
        if (StringUtils.isNotBlank(ids)) {
            try {
                // 批量删除字典明细数据
                sysDictService.batchUpdateDictDetailStatus(super.convert2Long(ids), XypjConstants.NUMBER_ZERO,
                        XypjConstants.NUMBER_TWO);
            } catch (ServiceException e) {
                result = super.getFailedRestServiceResult(e.getMessage());
                ExceptionLogger.error(e);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("删除失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/updateDictDetail.json 更新字典明细信息
     * @apiName updateDictDetail
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {DictDetailEntity} entity 字典明细实体
     * @apiParam {String} dtlKey KEY值
     * @apiParam {String} dtlValue 字典值
     * @apiParam {int} orderBy 排序
     * @apiParam {int} enabled 是否使用，1否，2是
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":null}
     */
    @RequestMapping(value = "/updateDictDetail", method = RequestMethod.POST)
    public RestServiceResult<Object> updateDictDetail(@RequestBody DictDetailEntity entity) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();
        if (null != entity) {
            try {
                sysDictService.updateDictDetail(entity);
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("更新失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * @api {post} /sysdict/isExistDictDetail.json 根据字典明细键判断是否有重复数据
     * @apiName isExistDictDetail
     * @apiVersion 0.0.1
     * @apiGroup 字典管理
     * @apiParam {String} dtlKey 明细键
     * @apiParam {long} dictId 字典Id
     * @apiParam {long} dictDetailId 字典明细Id
     * @apiParamExample {json} 请求参数示例 {}
     * @apiSuccess {String} code 状态码:0 成功 -1 失败
     * @apiSuccess {String} msg 错误信息
     * @apiSuccess {int} count 结果集数据量
     * @apiSuccess {String} data 结果集
     * @apiSuccess {String} flag true 存在重复, false 不存在重复
     * @apiSuccessExample {json} 成功返回结果
     * {"code":0,"msg":null,"count":0,"data":{"flag":"true"}}
     */
    @RequestMapping(value = "/isExistDictDetail", method = RequestMethod.POST)
    public RestServiceResult<Map<String, String>> isExistDictDetail(String dtlKey, long dictId,
                                                                    @RequestParam(value = "dictId", required = false, defaultValue = "0") long dictDetailId) {
        RestServiceResult<Map<String, String>> rstData = null;
        Map<String, String> result = new HashMap<>();
        String flag = "";
        if (StringUtils.isNotBlank(dtlKey) && dictId > XypjConstants.NUMBER_ZERO) {
            try {
                List<DictDetailEntity> datas = sysDictService.getDictDetailByKey(dictId, dictDetailId, dtlKey);
                if (!CollectionUtils.isEmpty(datas)) {
                    flag = "true";
                } else {
                    flag = "false";
                }
                result.put("flag", flag);
            } catch (Exception e) {
                rstData = super.getFailedRestServiceResult("查询失败！");
                ExceptionLogger.error(e);
            }
        }
        rstData = super.getSuccessRestServiceResult(result);
        return rstData;
    }

    /**
     * 获取指定字典详情值
     *
     * @param dictKey 字典值
     * @return RestServiceResult
     * @author YaoS
     * @date 10:07 18/11/9
     **/
    @RequestMapping(value = "/getDictDetails", method = RequestMethod.POST)
    public RestServiceResult<List<DictDetailEntity>> getDictDetails(
            @RequestParam(value = "dictKey", defaultValue = "", required = true) String dictKey,
            HttpServletRequest request) {
        RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
        try {
            List<DictDetailEntity> list = sysDictService.getDictDetails(dictKey, StringUtils.EMPTY);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("获取字典详情值失败！");
            return result;
        }
        return result;
    }
    
    @RequestMapping(value = "/getDictDetailsBylen", method = RequestMethod.POST)
    public RestServiceResult<List<DictDetailEntity>> getDictDetailsBylen(
            @RequestParam(value = "dictKey", defaultValue = "", required = true) String dictKey,
            HttpServletRequest request) {
        RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
        try {
            List<DictDetailEntity> list = sysDictService.getDictDetailsBylen(dictKey, StringUtils.EMPTY);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("获取字典详情值失败！");
            return result;
        }
        return result;
    }

    /**
     * 获取字典详情值
     *
     * @param dictKey 字典值
     * @param dtlKey  字典详情值，下拉列表的话设置为空
     * @return RestServiceResult
     * @author YaoS
     * @date 10:07 18/11/9
     **/
    @RequestMapping(value = "/getDictDetail", method = RequestMethod.POST)
    public RestServiceResult<List<DictDetailEntity>> getDict(
            @RequestParam(value = "dictKey", defaultValue = "", required = true) String dictKey,
            @RequestParam(value = "dtlKey", defaultValue = "", required = true) String dtlKey,
            HttpServletRequest request) {
        RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
        try {
            List<DictDetailEntity> list = sysDictService.getDictDetails(dictKey, dtlKey);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("获取字典详情值失败！");
            return result;
        }
        return result;
    }
}